/* Copyright (c) 2006-2011 by OpenLayers Contributors (see authors.txt for 
 * full list of contributors). Published under the Clear BSD license.  
 * See http://svn.openlayers.org/trunk/openlayers/license.txt for the
 * full text of the license. */

/**
 * Class: OpenLayers.LocalTileStorage
 * Class for access to SQL Web Storage or Web (local) Storage.
 * Allows you to store, retrieve and get information about what
 * is stored. 
 */


/**
 * @requires OpenLayers/Layer.js
 * @requires OpenLayers/LocalTileStorage/TileWebStorage.js
 * @requires OpenLayers/LocalTileStorage/TileSQLStorage.js
 */

OpenLayers.LocalTileStorage =  OpenLayers.Class({
    
    /**
     * Method: getURL
     * Return a GetMap query string for this layer or the data URI for this 
     * image from local storage. To be used as the img src.
     *
     * Parameters:
     * url - {<String>} The URL we want to test.
     *
     * Returns:
     * {String} a GetMap query string for this layer or the data URI for this 
     * image from local storage. To be used as the img src.
     */
     getCacheURL: function (url, tile) {
        
    	// If we want to use the local cache, check to see if they exist and 
    	// use those values if they do.
        if (this.params.ENABLELOCALCACHE) {        

	        // check to see if the tile exists in the cache
    		var hc = NG.util.HashCode.value(url);
	        var imageCached = this.store.get(hc, tile.imgDiv);	    	 
	        	
	        if (imageCached) {
	        	return imageCached;
	        } 
	    	
    	} 
    	
        return url;
        	
    },
    
    /**
     * Note the area stored will depend on the buffer value that has been set.
     */
    cacheAreaViewed:function() {

	    	// Go through all the tiles in the current view and get their URL.
	    	for (var i=0; i<this.layer.grid.length; i++) {
	    		for (var j=0; j<this.layer.grid[i].length; j++) {

	    			if (this.layer.grid[i][j].url) {
		    			// before we can store the image we need to proxy to if it comes 
		    			// from another domain.
		    			var proxiedURL = this.getProxiedURL(this.layer.grid[i][j].url);
		    			
		    			this.layer.grid[i][j].imgDiv.onload = OpenLayers.Function.bindAsEventListener(this.cacheTile ,this.layer.grid[i][j]);	    			
		    			this.layer.grid[i][j].imgDiv.src = proxiedURL;	    				
	    			}
	    		}
	    	}
        
    	return false;
    },
	
    getProxiedURL: function(url) {
    	return url = url + "&x=" + Math.random();
    },
    
    _getProxiedURL: function(url) {
    	
    	// Check if the map being requested is on the same domain/port
        var sameOrigin = !(url.indexOf("http") == 0);
        var urlParts = !sameOrigin && url.match(this.URL_SPLIT_REGEX);
        if (urlParts) {
            var location = window.location;
            sameOrigin =
                urlParts[1] == location.protocol &&
                urlParts[3] == location.hostname;
            var uPort = urlParts[4], lPort = location.port;
            if (uPort != 80 && uPort != "" || lPort != "80" && lPort != "") {
                sameOrigin = sameOrigin && uPort == lPort;
            }
        }
     
        var proxiedURL;
        // For proxy need to url encode the params. 
        if (!sameOrigin && OpenLayers.ProxyHost) {
        	proxiedURL = OpenLayers.ProxyHost+encodeURIComponent(url);
        } else if (!sameOrigin){
            OpenLayers.Console.warn(
                    OpenLayers.i18n("proxyNeeded"), {url: url});
        }
        
        return proxiedURL;
    },
    
    cacheTile: function(e) {
    
		var canvas = document.createElement("canvas");
		canvas.width = this.size.w;
		canvas.height = this.size.h;
		var ctx = canvas.getContext("2d");
		ctx.drawImage(this.imgDiv, 0, 0);
		// Below does not work in FireFox
		//var imageData = canvas.toDataURL(this.params.FORMAT,'quality=20');
		var imageData = canvas.toDataURL();	    				    		    
    	
		// store under original URL
		var hc = NG.util.HashCode.value(this.getCacheKey());
		this.layer.store.set(hc, imageData);  
		
		this.imgDiv.onload = {};
    },    

  CLASS_NAME: "OpenLayers.LocalTileStorage"
});